﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StoragePeriod.Data;
using StoragePeriod.Common;
using System.Collections;
using System.Text;
using System.Web.Script.Serialization;
using StoragePeriod.Web.Common;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.Util;
using StoragePeriod.BLL.FoodTesting;
using StoragePeriod.Model.FoodTesting;
using StoragePeriod.Model.RawDict;
using StoragePeriod.BLL.RawDict;

namespace StoragePeriod.Web.FoodTesting
{
    public partial class SenseScore : SecurityPage
    {
        public List<Grading> Data_Grading = null;
        public List<GradingInfo> Data_GradingInfo = null;
        T_ScoreData tScoreData = new T_ScoreData(); //感官评分操作
        T_RawMaterial tRawMaterial = new T_RawMaterial();//原料操作

        public override string PrivCode()
        {
            return "918f165ec06c9bb";
        }

        private void BingRep()
        {
            if (this.HidRawID.Value == "")
                return;

            E_RawMaterial md = tRawMaterial.GetModel(int.Parse(this.HidRawID.Value));

            int TypeId =Convert.ToInt32(md.PeriodTypeID);
            RawMaterialType RawTypeInfoMd = RawMaterialType.Where("id=@0",TypeId).First();

            using (StoragePeriodDataContext data = new StoragePeriodDataContext())
            {
                Data_Grading = data.Grading.Where("Temp1=@0", RawTypeInfoMd.ParentId.ToString()).ToList();
            }
        }

        public void Get_GradingInfo(int Gradingid)
        {
            using (StoragePeriodDataContext data = new StoragePeriodDataContext())
            {
                Data_GradingInfo = data.GradingInfo.Where(p=>p.GradingId==Gradingid).ToList();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ((ScriptManager)(Master.FindControl("ContentScriptManager").FindControl("ScriptManager1"))).RegisterPostBackControl(Btn_Export); //未了解决使用 UpLoadPanl 而无法输出文件的问题

            this.LeftTree.SelectedChanging += new UserControls.MaterialTree.TreeEventDelegate(LeftTree_SelectedChanging);
            this.BingRep();
            if (IsPostBack) return;
        }

        public List<DataTimeTitle> strDateList;
        public List<List<AssayDataList>> Assdatalist;
        protected void Btn_SearchFX_Click(object sender, EventArgs e)
        {
            string RawIDList = this.HidRawListId.Value;
            if (RawIDList == "")
            {
                ScriptManager.RegisterStartupScript(this.Btn_SearchFX, this.GetType(), "alert", "<script>$(document).ready(function () { TreeRadioOrMulti();alert('请选择原料！');});</script>", false);
                return;
            }

            DateTime startTime = Convert.ToDateTime(this.txt_DateStart.Text);
            DateTime endTime = Convert.ToDateTime(this.txt_DateEnd.Text);

            if (RawIDList == "") return;

            if (this.HidShowId.Value == "0")
            {
                strDateList = new List<DataTimeTitle>();
                int index = 0;
                for (DateTime time = startTime; time <= endTime; time = time.AddDays(1))
                {
                    bool IsExists = false;
                    foreach (string RawId in RawIDList.Split(','))
                    {
                        if (ScoreData.Where("ScoreTime=@0 and RawId=@1", time, int.Parse(RawId)).Count() > 0)
                        {
                            IsExists = true;
                            break;
                        }
                    }
                    if (IsExists)
                    {
                        strDateList.Add(new DataTimeTitle() {StrTime = time.ToString("MM月dd日"), Time=time,Index=index});
                        index += 1;
                    }
                }

                Assdatalist = new List<List<AssayDataList>>();
                foreach (string RawID in RawIDList.Split(','))
                {
                    List<AssayDataList> datalist = new List<AssayDataList>();
                    string strRawName = RawMaterial.Where("id=@0", int.Parse(RawID)).First().RAWName;
                    double SumScore=0;
                    if (strDateList.Count > 0)
                    {
                        for (int i = 0; i < strDateList.Count; i++)
                        {
                            IQueryable<ScoreData> data = ScoreData.Where("ScoreTime=@0 and RawId=@1", strDateList[i].Time, int.Parse(RawID));
                            if (data.Count() > 0)
                            {
                                SumScore = data.Sum(p => p.Score);
                            }
                            datalist.Add(new AssayDataList() { AssayScore = SumScore, AssayTime = strDateList[i].Time, RawName = strRawName, RawId = int.Parse(RawID), IsSelectRaw = 0 });
                        }
                    }
                    else
                    {
                        datalist.Add(new AssayDataList() { AssayScore = SumScore, RawName = strRawName, RawId = int.Parse(RawID), IsSelectRaw = 1 });
                    }
                    Assdatalist.Add(datalist);
                }
            }
            else
            {
                UtilityUI.Load(this.UpdatePanel1, "SetShowPage();loadReport();");
            }

            ScriptManager.RegisterStartupScript(this.Btn_SearchFX, this.GetType(), "alert", "<script>$(document).ready(function () { TreeRadioOrMulti();SetShowPage(); });</script>", false);
        }

        protected void LeftTree_SelectedChanging(Dictionary<string, string> dic)
        {
            this.lab_RawName.Text = dic.Count > 0 ? dic.First().Value : "";
            this.HidRawID.Value = dic.Count > 0 ? dic.First().Key : "";

            this.BingRep();

            if (this.HidPageId.Value == "1")
            {
                if (dic.Count > 0)
                {
                    Assdatalist = new List<List<AssayDataList>>();
                    string SelectRaw = "";
                    string SelectRawName = "";
                    dic.ToList().ForEach(p =>
                    {
                        List<AssayDataList> datalist = new List<AssayDataList>();
                        SelectRaw += p.Key + ",";
                        SelectRawName += p.Value + ",";
                        datalist.Add(new AssayDataList() { RawName = p.Value, IsSelectRaw = 1 });
                        Assdatalist.Add(datalist);
                    });
                    this.HidRawListId.Value = SelectRaw.TrimEnd(',');
                    this.lab_RawListName.Text = SelectRawName.TrimEnd(',');
                }
                ScriptManager.RegisterStartupScript(this.Btn_SearchFX, this.GetType(), "alert", "<script>$(document).ready(function () { SetShowPage();TreeRadioOrMulti(); });</script>", false);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Btn_SearchFX, this.GetType(), "alert", "<script>$(document).ready(function () { TreeRadioOrMulti(); });</script>", false);
            }

        }

        protected void Btn_Save_Click(object sender, EventArgs e)
        {
            string strValue = this.HidScoreData.Value.TrimEnd(',');
            if (strValue == "") return;

            DateTime date=DateTime.Parse(this.txt_date.Text.Trim().EToString());
            int RawId=Convert.ToInt32(this.HidRawID.Value);

            E_ScoreData eScoreData = new E_ScoreData();
            eScoreData.RawId = RawId;
            eScoreData.ScoreTime = date;
            tScoreData.RemoveByTime(eScoreData);
            foreach (string str in strValue.Split(','))
            {
                E_ScoreData Score = new E_ScoreData();
                Score.GradingId = Convert.ToInt32(str.Split('-')[1]);
                Score.RawId = Convert.ToInt32(this.HidRawID.Value);
                Score.Score = Convert.ToInt32(str.Split('-')[0]);
                Score.ScoreTime = Convert.ToDateTime(this.txt_date.Text.Trim());
                tScoreData.Add(Score);
            }

            ScriptManager.RegisterStartupScript(this.Btn_Search, this.GetType(), "alert", "<script>TreeRadioOrMulti();alert('保存成功！');</script>", false);
        }

        protected void Btn_Search_Click(object sender, EventArgs e)
        {
            DateTime date=Convert.ToDateTime(this.txt_date.Text.Trim());
            int RawID = Convert.ToInt32(this.HidRawID.Value);
            string strValue = "";
            E_ScoreData eScoreData = new E_ScoreData();
            eScoreData.RawId = RawID;
            eScoreData.ScoreTime = date;
            List<E_ScoreData> ScoreDataList = tScoreData.GetDataEntityByTime(eScoreData);
            if (ScoreDataList != null)
            {
                foreach (E_ScoreData score in ScoreDataList)
                {
                    strValue += score.Score + "-" + score.GradingId + ",";
                }
            }
            this.HidScoreData.Value = strValue.TrimEnd(',');
            ScriptManager.RegisterStartupScript(this.Btn_Search, this.GetType(), "alert", "<script>$(document).ready(function () { TreeRadioOrMulti();SetTxtValue();SetRawSumScore(); });</script>", false);
        }

        protected void Btn_Del_Click(object sender, EventArgs e)
        {
            DateTime date = Convert.ToDateTime(this.txt_date.Text.Trim());
            int RawID = Convert.ToInt32(this.HidRawID.Value);
            E_ScoreData eScoreData = new E_ScoreData();
            eScoreData.RawId = RawID;
            eScoreData.ScoreTime = date;
            tScoreData.RemoveByTime(eScoreData);
            ScriptManager.RegisterStartupScript(this.Btn_Search, this.GetType(), "alert", "<script>TreeRadioOrMulti();alert('删除成功！');</script>", false);
        }

        /// <summary>
        /// 导出Execl
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Btn_Export_Click(object sender, EventArgs e)
        {
            List<Grading> Gradinglist = new List<Grading>(); //感官评分大类
            List<E_ScoreData> RawScorelist = new List<E_ScoreData>();//原料得分
            //获取遍历数据源
            DateTime date = Convert.ToDateTime(this.txt_date.Text.Trim());
            int RawID = Convert.ToInt32(this.HidRawID.Value);
            RawMaterial md = RawMaterial.Where("id=@0", RawID).First();
            int TypeId = Convert.ToInt32(md.PeriodTypeID);
            RawMaterialType RawTypeInfoMd = RawMaterialType.Where("id=@0", TypeId).First();
            using (StoragePeriodDataContext data = new StoragePeriodDataContext())
            {
                Gradinglist = data.Grading.Where("Temp1=@0", RawTypeInfoMd.ParentId.ToString()).ToList();
            }
            E_ScoreData eScoreData = new E_ScoreData();
            eScoreData.RawId = RawID;
            eScoreData.ScoreTime = date;
            RawScorelist = tScoreData.GetDataEntityByTime(eScoreData);

            MemoryStream mstest = new MemoryStream();
            using (IWorkbook workbook = new HSSFWorkbook())
            {
                using (ISheet sheet = workbook.CreateSheet("感官评分"))
                {
                    IRow hearder = sheet.CreateRow(0);
                    hearder.Height = 30 * 20;
                    ICell cell = hearder.CreateCell(0);
                    cell.SetCellValue(md.RAWName + "（" + this.txt_date.Text.Trim() + "）");
                    ICellStyle style = workbook.CreateCellStyle();
                    style.Alignment = HorizontalAlignment.CENTER;
                    style.VerticalAlignment = VerticalAlignment.CENTER;
                    IFont font = workbook.CreateFont();
                    font.FontHeight = 20 * 20;
                    style.SetFont(font);
                    cell.CellStyle = style;
                    sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 3));

                    int rowindex = 1;
                    //显示内容
                    Gradinglist.ForEach(p =>
                    {
                        IRow rowitem = sheet.CreateRow(rowindex);
                        E_ScoreData ScoreMd = RawScorelist.Where(i => i.GradingId == p.id).FirstOrDefault();
                        rowitem.CreateCell(0).SetCellValue(ScoreMd != null ? ScoreMd.Score : 0);
                        rowitem.CreateCell(1).SetCellValue(p.GradingName);

                        List<GradingInfo> listinfoitem = GradingInfo.Where("GradingId=@0", p.id).ToList();
                        bool IsOneRow = true;
                        listinfoitem.ForEach(u =>
                        {
                            if (IsOneRow)
                            {
                                rowitem.CreateCell(2).SetCellValue(u.GradingTitle);
                                rowitem.CreateCell(3).SetCellValue(u.ScoresRange);
                                IsOneRow = false;
                            }
                            else
                            {
                                rowindex++;
                                IRow rowinfoitem = sheet.CreateRow(rowindex);
                                rowinfoitem.CreateCell(2).SetCellValue(u.GradingTitle);
                                rowinfoitem.CreateCell(3).SetCellValue(u.ScoresRange);
                            }
                        });
                        sheet.AddMergedRegion(new CellRangeAddress(rowindex - listinfoitem.Count + 1, rowindex, 0, 0));
                        sheet.AddMergedRegion(new CellRangeAddress(rowindex - listinfoitem.Count + 1, rowindex, 1, 1));
                        rowindex++;
                    });


                    //设置样式
                    ICellStyle rowStyle = workbook.CreateCellStyle();
                    rowStyle.Alignment = HorizontalAlignment.CENTER;
                    rowStyle.VerticalAlignment = VerticalAlignment.CENTER;
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row != null)
                        {
                            for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                            {
                                if (row.GetCell(j) != null)
                                    row.GetCell(j).CellStyle = rowStyle;
                            }
                        }
                    }

                    workbook.Write(mstest);
                    mstest.Flush();
                    mstest.Position = 0;
                }
            }

            string fileName = Guid.NewGuid().ToString()+".xls";
            if (HttpContext.Current.Request.Browser.Browser == "IE")
                fileName = HttpUtility.UrlEncode(fileName);
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
            HttpContext.Current.Response.BinaryWrite(mstest.ToArray());
        }

    }
}